package com.example.mybatisplusdemo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplusdemo.Result.Result;
import com.example.mybatisplusdemo.Service.AdminService;
import com.example.mybatisplusdemo.Service.RoleService;
import com.example.mybatisplusdemo.pojo.Admin;
import com.example.mybatisplusdemo.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.Methods.methods;



@RestController
@RequestMapping("/api")
@CrossOrigin
public class LoginController {
    @Autowired
    AdminService adminService;
    @Autowired
    RoleService roleService;

    @RequestMapping("/index")
    public String hello(){
        return "hello world ";
    }
    /**
     * 登录方法
     * @param admin
     * @return json
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result AdminLogin(@RequestBody Admin admin){
        String LoginUsername = admin.getUsername();
        String LoginPassword = admin.getPassword();
        String md5Password = new methods().md5(LoginPassword);
        int count = adminService.count(new QueryWrapper<Admin>().
                eq("username", LoginUsername).
                eq("password", md5Password));
        if (count != 0){
            Admin one = adminService.getOne(new QueryWrapper<Admin>().select("roleId").
                    eq("username", LoginUsername).eq("password", md5Password));
            Role role = roleService.getOne(new QueryWrapper<Role>()
                    .select("roleName").eq("id", one.getRoleId()));
            admin.setPassword(md5Password);
            admin.setRolename(role.getRoleName());
            return new Result(200,"登录成功！",admin);
        }else{
            return new Result(400,"账号或者密码错误！");
        }
    }

    @RequestMapping(value = "/logintest",method = RequestMethod.POST)
    public Result AdminLogintest(@RequestParam("username") String username,@RequestParam("password") String password){
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(password);
        return new Result(200,"msg",admin);
    }
}
